﻿
<div class="ui-widget" id="AddStep1">
    <div class="ui-widget-header"><span class="ui-icon ui-icon-document ilb"/>Add Data Set (1/3)</div>
    <div class="ui-widget-content">
        
        <form enctype="multipart/form-data" id="UploadForm">
        <p>            
            Data Set File: <input type="file" id="datafile" name="datafile" />
            <input type="hidden" name="method" value="UPLOADDATASET" />
        </p>
        <p>
            Data Set Name: <input type="text" id="DataSetName" name="DataSetName" />
        </p>

  

        <p>
            Comments Start with (separate multiples with comma like "|,\"): <input type="text" id="CommentsStep1" value="\,|" />                
        </p>

        <p>

                <span class="my-button" icon="ui-icon-arrow-1-n" onclick="TryUploadFile();">Upload</span>
        </p>


        
        </form>

        <div class="uploadProgress" />

    </div>
</div>

<div class="" id="AddStep2">
    <div class="ui-widget">

    <div class="ui-widget-header">
        <span class="ui-icon ui-icon-document ilb"/>Add Data Set (2/3)
    </div>
    <div class="ui-widget-content">

        <h4>
         Example Data:
            </h4>
        
        <textarea id="datasetSample" style=" width: 90%; height: 150px; white-space: nowrap; overflow:auto;"></textarea>

        <p>
            Comment Lines (separate with commas): <input type="text" id="CommentChars" value="\,|" />
        </p>

        <p>
            Detailed information on regular expressions is available at <a target="_blank" href="http://www.regularexpressions.info">RegularExpressions.info</a>
        </p>

      <div id="SourceRegexItems"></div>    
      <div id="RegexDroppable" class="ui-state-default"></div>        
      <div id="RegexText" class="ui-widget-content"></div>

      
       
        
        </div>
       </div>

        <div class="ui-widget">
           <div id="UnitMapping" class="ui-widget-header">Unit Mapping</div>
            <div class="ui-widget-content">
                <p>
                For the required fields listed, select the correct unit type from the dropdown
                </p>
               <table>
                   <tr>
                   <th>ra/decl:</th>
                       <td> 
                           <select id="radeclUnitMap">
                                <option value="radecl">GLat/GLon</option>                                                          
                             </select> 

                           <a href="https://galactic.codeplex.com" target="_blank" class="">Need another input unit? Submit a request on Codeplex.</a><span class="ui-icon ui-icon-extlink ilb"/>

                       </td>

               </tr>
                   </table>
                   
                </div>
           </div> 
        

       <div id="RegexResult" style="margin-top: 10px;" class="ui-widget">
           <div class="ui-widget-header">Required Fields</div>
           <div class="ui-widget-content">
               <p>
                   Drag the field names below onto the column headers in the example table below:
               </p>

               <div id="ColumnNameMapper" class="ui-widget-content">

               </div>

               <table id="CapturesTable">
                  <thead>
                 
                  
                  </thead>
                  <tbody></tbody>
                </table>

               <table class="my-table">
                
               </table>
           </div>
        </div>

    <div class="ui-widget">
        <div class="ui-widget-header">Continue...</div>
        <div class="ui-widget-content">
            <p>Click Next to save the Dataset format data</p>
            <p>
                <span class="my-button" icon="ui-icon-arrowthick-1-e" onclick="TryMoveToStep3();">Next</span>
            </p>
        </div>
    </div>
</div>    
            

  


<div class="ui-widget" id="AddStep3">
    <div class="ui-widget-header"><span class="ui-icon ui-icon-document ilb"/>Add Data Set (3/3)</div>
    <div class="ui-content">

        <div class="ui-widget" style="">
            <div class="ui-widget-header">Summary</div>
            <div class="ui-widget-content">
                <table id="SummaryTable" class="my-table">


                </table>


                <div class="my-form">
            <p>
                Email me when data is loaded: <input type="checkbox" id="EmailWhenComplete" checked />
            </p>
            <p>
                Pushover notification when data is loaded: <input type="checkbox" id="PushoverWhenComplete" checked />
            </p>
            <p class="my-button-row">
                <span class="my-button" icon="ui-icon-disk" onclick="SaveDataSetLoadRequest();">Save Properties & Queue Data Load</span>
            </p>
        </div>

            </div>
        </div>

        

    </div>
</div>



<script type="text/javascript">

    ///<reference path="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js" />
    ///<reference path="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js" />
    ///<reference path="js/lib.js" />

    var RequiredParameters = new Array("GalaxyName", "glon", "glat", "Morphology", "v");


    var arrayOfObjects =
    [
        {
            text: "Start of Line",
            regex: "^"
        },
        {
            text: "Any + EOL",
            regex: ".*$"
        },
        {
            text: "Tab",
            regex: "\\t+"
        },
        {
            text: "Whitespace",
            regex: "\\s+"
        },
        {
            text: "(Letters & Numbers)",
            regex: "([a-zA-Z0-9]+)"
        },
        {
            text: "(Non-Whitespace)",
            regex: "(\\S+)"
        }

    ];


        /*
        @DataSetId	bigint,
@GalaxyName varchar(30),
@ra decimal,
@decl decimal,
@Morphology varchar(30)
        */

    function PrepDraggables()
    {

        $("#ColumnNameMapper").empty();
        for (var i = 0; i < RequiredParameters.length; i++)
        {
            var p = RequiredParameters[i];
            //console.log(p);

            var n = $("<span>").text(p);

            $("#ColumnNameMapper").append(n);

        }

        $("#ColumnNameMapper > span").draggable(
            {
                cursor: "move",
                revert: "invalid" /* function (dropped)
                {
                    console.log("revert called");
                    var d = $(this);
                    console.log("revert draggable ShouldREvert:" + d.data("shouldRevert"));
                    if (d.data("shouldRevert") == true)
                    {
                        console.log("reverting...");
                       
                      
                        return false;
                    }
                    else
                    {
                        console.log("not reverting");
                        return true;
                    }

                }*/
            }).addClass("ui-widget-content").addClass("columnNameMapperSpan ui-corner-all ilb").css("cursor", "move");

        $("#ColumnNameMapper").droppable(
        {
            activeClass: "ui-state-active",
            hoverClass: "ui-state-hover",
            drop: function (ev, ui)
            {
                var dropped = ui.draggable;
                var droppedOn = $(this);
                //dropped.data("shouldRevert", false);
                //console.log("columnamemapper droppable ShouldREvert:" + dropped.data("shouldRevert"));
                var lastParent = dropped.data("lastParent");
                dropped.data("num", "");
               // console.log("num of last parent: " + lastParent.data("num"));
                
                //dropped.data("shouldRevert", false);
                dropped.detach().css({ top: 0, left: 0 }).removeClass("ui-state-highlight");
                droppedOn.append(dropped);
                lastParent.text(lastParent.data("num"));

            }


        }).css({ height: 35 });
    }

    function TryMoveToStep3()
    {
        var ok = true;
        $("#ColumnNameMapper").removeClass("ui-state-highlight");
        if ($("#ColumnNameMapper").children().length > 0)
        {
            ok = false;
            GrowlHighlight("You must map all Galactic data fields to the input table");
            $("#ColumnNameMapper").addClass("ui-state-highlight");
        }

        if (ok)
        {
            $("#AddStep2").hide();
            InitializeStep3();
        }
    }

    $(document).ready(function ()
    {
      
        PrepDraggables();

        $("#AddStep2, #AddStep3, #AddStep4").hide();

        
        $("#datafile").change(function ()
        {
            var file = this.files[0];
            var name = file.name;

            //console.log("datafile name is: " + name);
            $("body").data("DataFileName", name);
        });
       

    });

   /*/ function GenerateRegex()
    {

        var rt = $("#RegexText");

        rt.empty();

        $("#RegexDroppable .ui-regex-source").each(function (key)
        {
            rt.append($(this).data("regex"));

        });

        UpdateCapturesTable();

        $("#regex").val(final);
        RunRegexTest();
    }*/

    function UpdateRegexText()
    {
        var rt = $("#RegexText");

        rt.empty();

        $("#RegexDroppable .ui-regex-source").each(function (key)
        {
            //alert($(this).data("regex"));

            rt.append($(this).data("regex"));

        });

        UpdateCapturesTable();
    }


    function UpdateCapturesTable()
    {
        //alert($("#RegexText").text());
        var pattern = new RegExp($("#RegexText").text(), "im");
        //console.log("pattern: " + pattern);
        //alert(pattern);
        var s = new String($("#datasetSample").val());
        var thead = $("#CapturesTable thead");
        var tbody = $("#CapturesTable tbody");
        thead.empty();
        tbody.empty();

        var items = s.split("\n");
       // console.log(s);
        // console.log(items);
        console.log(items.length);
        //  alert(items.length);

        if (items.length == 0)
        {
            thead.append("no matches/captures");
            return
        }

        var tbl = $("#CapturesTable thead");
        tbl.empty();

        var headerRowCreated = false;


        for (var i = 0; i < items.length; i++)
        {




            var r = $("<tr>");
            var item = items[i];
           // console.log("item: " + item);
            var columns = pattern.exec(item);
            // alert(s);
            //alert(columns);
            //console.log("columns: " + columns);
            if(columns == null)
                        continue;

            if (!headerRowCreated)
            {
                var row = $("<tr id='ResultLabelRow'>");

                for (var c = 1; c <= columns.length; c++)
                {
                    var th = $("<th style='width: 100px;'>" + c + "</th>").data("num", c);
                    row.append(th);
                }

                row.children("th").droppable(
                  {
                      drop: function (evt, ui)
                      {
                          var dropped = ui.draggable;
                          var droppedOn = $(this);

                         // console.log("children.length: " + droppedOn.children().length);

                          if (droppedOn.children().length > 0)
                          {
                             // console.log("setting shouldRevert to true");
                              dropped.data("shouldRevert", true);
                            //  console.log("from data: " + dropped.data("shouldRevert"));
                              return;
                          }



                          if (dropped.parent().is("th"))
                          {
                              dropped.parent().text(dropped.data("num"));
                          }



                          /*dropped.click(function ()
                          {
                              dropped.detach().click(null);
                              $("#ColumnNameMapper").append(dropped);                                
                              droppedOn.text(droppedOn.data("num"));                                
                          });*/

                          //console.log(droppedOn);
                         // console.log("children.length before move " + droppedOn.children().length);


                          // var shouldRevert = droppedOn.children().length > 0;

                          $(dropped).detach().css({ top: 0, left: 0 }).addClass("ui-state-highlight");
                          $(droppedOn).text("").append(dropped);

                        //  console.log("children.length after move " + droppedOn.children().length);

                          if (dropped.data("lastParent") != null)
                          {
                              var l = dropped.data("lastParent");
                              l.text(l.data("num"));
                          }

                          $(dropped).data("lastParent", droppedOn);
                          // dropped.data("shouldRevert", shouldRevert);

                          // $(dropped).detach().css({ top: 0, left: 0 });
                          //droppedOn.text("");//.append(dropped);

                          // console.log("from data after empty: " + dropped.data("shouldRevert"));

                         // console.log("num: " + $(this).data("num"));
                          $(dropped).data("num", $(this).data("num"));
                         // console.log("data off dropped object: " + $(dropped).data("num"));
                          //if (!shouldRevert)
                          // {
                          //     var lastParent = dropped.data("lastParent");
                          //    console.log("num of last parent: " + lastParent.data("num"));
                          //    lastParent.text(lastParent.data("num"));
                          //  }

                          // console.log("Should Revert: " + shouldRevert);


                          // console.log(droppedOn.children().length);

                      },


                      activeClass: "ui-state-active",
                      hoverClass: "ui-state-hover"
                  }).addClass("columnNameMapperTh");

                tbl.append(row);

                headerRowCreated = true;
            }


           // r.append($("<th>").text(i + 1));

            for (var j = 1; j < columns.length; j++)
            {
                //lert(j + "\n" + columns[j]);

                var td = $("<td>");

                td.text(columns[j]);
                r.append(td);

            }
            tbody.append(r);
        }

        PrepDraggables();

    }

      
    function SaveDataSetLoadRequest()
    {

        //var DataSetOptions = sessionStorage.getItem("DataSetOptions");
        //store data set configuration
        GetJsonSproc("usp_SetDataSetParameters",
            {
                DataSetId: DataSetOptions.Id,
                Regex: DataSetOptions.Regex,
                FieldMap: DataSetOptions.FieldMapString,
                CommentMarkers: DataSetOptions.CommentChars
            },
            function (json)
            {
                //log request for processing
                GetJsonSproc("usp_AddDataSetLoadRequst",
                    {
                        DataSetId: DataSetOptions.Id,
                        UserName: GetUsername(),
                        //FilePath: DataSetOptions.DataSetFileName,
                        Email: $("#EmailWhenComplete").is(":checked"),
                        Pushover : $("#PushoverWhenComplete").is(":checked")
                    },
                    function (json)
                    {                        
                        $("#AddStep3").hide();
                        InitializeStep4();

                    });
            });
    }

    function progressHandlingFunction(e)
    {
      //  console.log("callback in progresshandlingfunction");
        if (e.lengthComputable)
        {
            //$('progress').attr({ value: e.loaded, max: e.total });
        }
    }

    function InitializeStep2()
    {

        for (var i = 0; i < arrayOfObjects.length; i++)
        {
            var object = arrayOfObjects[i];

            var s = $("<span>").attr("title", "Click to add").tooltip().disableSelection().text(object.text);
            var icon = $("<span class='ui-icon ui-icon-plus ilb'>");
            s.addClass("ui-regex-source ui-state-default ui-corner-all");
            s.append(icon);
            s.data("regex", object.regex);
            $("#SourceRegexItems").append(s);


            //     alert(object.text + ',' + object.regex);
        }


        $("#RegexDroppable").sortable(
        {
            refreshPositions: true,
            placeholder: "ui-state-highlight placeholder ui-corner-all",
            forcePlaceholderSize: true,
            //containment: "parent",
            opacity: 0.5,
            tolerance: "pointer",


            start: function (evt, ui)
            {
                //  ui.placeholder.css("width", $(this).width()).addClass("ilb");
            },

            update: function (evt, ui)
            {
                UpdateRegexText();
            }
        }).disableSelection();


        $("#SourceRegexItems span.ui-regex-source").click(function ()
        {
            var s = $(this).clone(true);
            s.tooltip("disable").attr("title", null).unbind("click").children("span.ui-icon").removeClass("ui-icon-plus").addClass("ui-icon-circle-close").click(function ()
            {
                $(this).parent().remove();
                UpdateRegexText();
            }).attr("title", "Click to remove").tooltip();


            $("#RegexDroppable").append(s);



            UpdateRegexText();


        });


        $("#AddStep2 .ui-widget-header:first").text("Add Data Set(2/3): " + $("#DataSetName").val());

          
        $("#CommentChars").val($("#CommentsStep1").val());

        UnsavedWork(true);
        Growl("File Uploaded to server. Pulling preview data...");
        var maxSampleLines = 20;
        var commentLineStart = new String($("#CommentChars").val()).split(",");

        //console.log("start pull for data file");



        jQuery.get("temp/" + $("body").data("DataFileName"), function (txt)
        {
            //console.log(".get callback");
            var s = new String(txt);

            //console.log("data from server:" + s);

            //var lineRegex = new RegExp("[\\r\\n]", "g");
            items = s.split(/\r\n|\r|\n/g);
            var lines = new Array();
            var linesNow = 0;
            for (var i = 0; i < items.length; i++)
            {
                var item = items[i];
                var firstChar = item.substr(0, 1);
                var isComment = false;
                for (var j = 0; j < commentLineStart.length; j++)
                {
                    // console.log("firstChar: " + firstChar + " - commentStartLineitem: " + commentLineStart[j]);
                    if (firstChar == commentLineStart[j])
                    {
                        isComment = true;
                        break;
                    }
                }

                if (isComment)
                    continue;

                lines.push(item);
                linesNow++;
                if (linesNow >= maxSampleLines)
                    break;
            }

            $("#datasetSample").val(lines.join("\r\n"));

           // GenerateRegex();
            $("#AddStep2").show();
        }
        
        );
    }
    
    function InitializeStep3()
    {


        var st = $("#SummaryTable");
        st.empty();


        DataSetOptions =
        {
            Id : sessionStorage.getItem("DataSetId"),
            DataSetName: $("#DataSetName").val(),
            DataSetFileName: $("#datafile").val(),                
            //CapturedColumnCount: $("#ColumnCount").val(),
            //Delimeter: $("#Delimeter").val(),
            Regex: $("#RegexText").text(),
            RaDeclUnitMap: $("#radeclUnitMap").val(),
            CommentChars: $("#CommentChars").val()
        }

        var fieldMap = {};

        $.each($("#ResultLabelRow TH span"), function(index, el)
       {
           //console.log("in .each");
          // console.log(el);
          // console.log($(this));           

           DataSetOptions[$(this).text()] = $(el).data("num");

           fieldMap[$(this).text()] = $(el).data("num");
       });

       //console.log(DataSetOptions);

      // sessionStorage.setItem("DataSetOptions", DataSetOptions);

       $("#SummaryTable").empty();
       $.each(DataSetOptions, function (key, value)
       {
           var row = $("<tr>");

           row.append($("<th>").text(key));
           row.append($("<td>").text(value));

           $("#SummaryTable").append(row);
       });

       var FieldMapString = "";
       var processed = 0;
       
       $.each(fieldMap, function (key, value)
       {
           processed++;
           FieldMapString += key + "=" + value;

           if (RequiredParameters.length > processed)
               FieldMapString += ",";
       });

       //console.log("Field Map string: " + FieldMapString);
       DataSetOptions["FieldMapString"] = FieldMapString;

       $("#AddStep3").show();

       

        
    }

    function InitializeStep4()
    {
        UnsavedWork(false);        
        DataSetOptions = null;
        Growl("Data load request queued.");
        NavigateToPage("TrackProgress.htm");
    }

    function IsFileUploadValid()
    {
        $("#UploadForm input").removeClass("ui-state-error");

        var ok = true;
        if (FieldIsEmpty("#DataSetName"))
            ok = false;
        if (FieldIsEmpty("#datafile"))
            ok = false;

        if (FieldIsEmpty("#CommentsStep1"))
            ok = false;

        if (FieldIsEmpty("#ColumnsToCaptureStep1"))
            ok = false;



        return ok;
    }

    function TryUploadFile()
    {

        if (!IsFileUploadValid())
            return;

        var formData = new FormData($('#UploadForm')[0]);
        
      

        $.ajax({
            url: 'WebService.aspx',  //server script to process data
            type: 'POST',
           dataType : "json",
            xhr: function ()
            {  // custom xhr
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload)
                { // check if upload property exists
                    //console.log("myXhr.upload is true");
                    myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // for handling the progress of the upload
                }
                return myXhr;
            },
            //Ajax events
            //beforeSend: beforeSendHandler,
            success: function (json)
            {
               // console.log(json);
                sessionStorage.setItem("DataSetId", json[0]["Id"]);
                $("#AddStep1").hide();
                InitializeStep2();
                

            },
            error: function (jqXHR, textStatus, errorThrown)
            {
                GrowlError("Error uploading data file: " + textStatus + " - " + errorThrown);
                //console.log("error posting datafile: " + textStatus + "\n" + errorThrown);
            },
            // Form data
            data: formData,
            //Options to tell JQuery not to process data or worry about content-type
            cache: false,
            contentType: false,
            processData: false
        });
    }

</script>